#!/bin/sh

# PROVIDE: pgbouncer
# REQUIRE: LOGIN
# BEFORE:  securelevel
# KEYWORD: shutdown

# Add the following lines to /etc/rc.conf to enable pgbouncer:
#
# pgbouncer_NAME_enable (bool): Set to "YES" to enable pgbouncer
#                               Default is "NO"
# pgbouncer_NAME_conf (str): Set path to config file
#                            /usr/local/etc/pgbouncer-NAME.conf
# Define profiles here to run separate pgbouncer instances:
#
# pgbouncer_profiles="foo bar"  Script uses /usr/local/etc/pgbouncer-NAME.conf respective
#                               For correct script working please update pidfile entries in
#                               pgbouncer-NAME.conf files.

. /etc/rc.subr

name="pgbouncer"
rcvar="${name}_enable"

extra_commands="reload"

command="/usr/local/bin/pgbouncer"
pidfile="/var/run/pgbouncer/$name.pid"

# read configuration and set defaults
load_rc_config "$name"
: ${pgbouncer_enable="NO"}
: ${pgbouncer_user="pgbouncer"}
: ${pgbouncer_conf="/usr/local/etc/$name.ini"}

command_args="-d ${pgbouncer_conf}"
required_files="${pgbouncer_conf}"

_profile_exists() {
	for _p in ${pgbouncer_profiles}; do
		[ "${_p}" = "$1" ] && return 1;
	done
	return 0
}

if [ $# -eq 2 ]; then
	_profile=$2
	_profile_exists $_profile
	_exists=$?
	[ ${_exists} -ne 1 ] && {
		echo "`basename /usr/local/etc/rc.d/pgbouncer`: no '$2' in 'pgbouncer_profiles'"
		exit 1
	};
	eval config_file="\${pgbouncer_${_profile}_conf:-}"
	if [ "x${config_file}" = "x" ]; then
		echo "You must define a configuration file (pgbouncer_${_profile}_conf)"
		exit 1
	fi
	eval pgbouncer_enable="\${pgbouncer_${_profile}_enable:-${pgbouncer_enable}}"
	echo "-- Profile: ${_profile} --"
	command_args="-d ${config_file}"
	pidfile="/var/run/pgbouncer/${_profile}.pid"
	required_files="${config_file}"
elif [ -n "${pgbouncer_profiles}" ]; then
	_profiles=${_profiles:-${pgbouncer_profiles}}
	for _profile in ${_profiles}; do
		/usr/local/etc/rc.d/pgbouncer $1 ${_profile}
	done
	exit 0
fi

run_rc_command "$1"
